package com.webull.information.center.carwler.task;

import java.util.List;
import java.util.function.Consumer;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import com.webull.information.center.carwler.common.model.StockTitle;
import com.webull.information.center.carwler.common.util.NewsTaskUtil;
import com.webull.information.center.carwler.task.handler.StockYahooNewsHandler;
import com.webull.securities.client.model.Stock2Information;
import com.webull.securities.client.service.StockService;

@Component
public class News_YahooFullStock_Task {
	protected final Logger logger = LogManager.getLogger(getClass());

	private @Autowired StockService stockService;
	private @Autowired StockYahooNewsHandler stockYahooNewsHandler;
	private @Autowired @Qualifier("executor_news") ThreadPoolTaskExecutor threadPoolTaskExecutor;
	private final Integer pageSize = 100;

	/**
	 * 全量扫描
	 *
	 * @since 0.1.0
	 */
	public Integer News_YahooFullStock_TaskExchangeCode(String exchangeCode) {
		return News_YahooFullStock_TaskExchangeCode(exchangeCode, -1, null);
	}

	public Integer News_YahooFullStock_TaskExchangeCode(String exchangeCode, Integer lastId, Integer loop) {
		logger.info(
				"News_YahooFullStock_Task.News_YahooFullStock_TaskExchangeCode start exchangeCode:{},lastId:{},loop:{}",
				exchangeCode, lastId, loop);
		int loop_ = 0;
		full: do {
			if (loop != null && loop > 0 && ++loop_ > loop) {
				break full;
			}
			List<Stock2Information> res = stockService.queryPagingInform(exchangeCode, lastId, pageSize);
			if (res == null || res.isEmpty()) {
				lastId = null;
				break full;
			}
			logger.info("News_YahooFullStock_Task.News_YahooFullStock_TaskExchangeCode stocks:" + res.size());
			lastId = res.get(res.size() - 1).getTickerId();
			procss(res);
		} while (true);

		return lastId;
	}

	private void procss(List<Stock2Information> res) {
		try {

			NewsTaskUtil.multiThreadProcess(res, process, threadPoolTaskExecutor);

			logger.info("News_YahooFullStock_TaskTask procss end:" + res.size());
		} catch (Exception e) {
			logger.error("News_YahooFullStock_TaskTask 全量新闻任务失败", e);
		}
	}

	private final Consumer<Stock2Information> process = input -> {
		StockTitle stockTitle = new StockTitle();
		BeanUtils.copyProperties(input, stockTitle);

		stockYahooNewsHandler.handlerByStockTitle4Yahoo(stockTitle);
		logger.info("News_YahooFullStock_Task.procss stockTitle:" + stockTitle);
	};
}
